<template>
  <div class="tab-content-box" :style="'min-height:' + (mainContextHeight - 76) + 'px'">
    <table-box
      class="page-table"
      :data="fragmentMyAgent.ProcessAgent.impl.dataList"
      :tree-config="{ rowField: 'id', parentField: 'parentId' }"
      @refresh="refreshFragmentMyAgent(true)"
    >
      <template v-slot:operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :icon="Plus"
          @click="onAddAgentClick()"
        >
          新建
        </el-button>
      </template>
      <vxe-column title="序号" type="seq" width="80px" tree-node />
      <vxe-column title="受委托人" field="delegateUserNames" show-overflow="title" />
      <vxe-column title="委托范围" show-overflow="title">
        <template #default="{ row }">
          {{ !row.isChild ? formatDelegateScope(row.delegateScope) : '' }}
        </template>
      </vxe-column>
      <vxe-column title="委托流程" show-overflow="title">
        <template #default="{ row }">
          {{ !row.isChild ? formatProcessDefinition(row.processDefinitionKeys) : '' }}
        </template>
      </vxe-column>
      <vxe-column title="开始时间">
        <template #default="{ row }">
          {{ !row.isChild ? row.startTime : '' }}
        </template>
      </vxe-column>
      <vxe-column title="结束时间">
        <template #default="{ row }">
          {{ !row.isChild ? row.endTime : '' }}
        </template>
      </vxe-column>
      <vxe-column title="委托状态">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row)" :size="layoutStore.defaultFormItemSize">
            {{ getStatusValue(row) }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column title="委托说明" field="memo" show-overflow="title">
        <template #default="{ row }">
          {{ !row.isChild ? row.memo : '' }}
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right" width="120px">
        <template #default="{ row }">
          <template v-if="!row.isChild">
            <el-button
              @click="onEditAgentClick(row)"
              type="primary"
              link
              :size="layoutStore.defaultFormItemSize"
            >
              编辑
            </el-button>
            <el-button
              @click="onDeleteClick(row)"
              link
              type="danger"
              :size="layoutStore.defaultFormItemSize"
            >
              删除
            </el-button>
          </template>
        </template>
      </vxe-column>
      <template v-slot:pagination>
        <el-row type="flex" justify="end" style="margin-top: 16px">
          <el-pagination
            :total="fragmentMyAgent.ProcessAgent.impl.totalCount"
            :current-page="fragmentMyAgent.ProcessAgent.impl.currentPage"
            :page-size="fragmentMyAgent.ProcessAgent.impl.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="fragmentMyAgent.ProcessAgent.impl.onCurrentPageChange"
            @size-change="fragmentMyAgent.ProcessAgent.impl.onPageSizeChange"
          >
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

<script setup lang="ts">
import { inject, reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { TableOptions } from '@/common/types/pagination';
import { useTable } from '@/common/hooks/useTable';
import { TableData } from '@/common/types/table';
import { ANY_OBJECT } from '@/types/generic';
import { useDialog } from '@/components/Dialog/useDialog';
import { useLayoutStore } from '@/store';
import FormEditAgent from './formEditAgent.vue';
import { FlowDelegateUserController, FlowEntryController } from '@/api/flow';
import { SysCommonBizController } from '@/api/system';
import { treeDataTranslate } from '@/common/utils';

const Dialog = useDialog();
const layoutStore = useLayoutStore();
const mainContextHeight = inject('mainContextHeight', 200);

const getStatusType = (row: ANY_OBJECT) => {
  // 如果是子行，直接返回确认状态的样式
  if (row.isChild) {
    switch (row.confirmStatus) {
      case 1:
        return 'success';
      case 2:
        return 'danger';
      default:
        return 'info';
    }
  }

  // 检查是否过期
  const now = new Date();
  const endTime = new Date(row.endTime);
  if (now > endTime) {
    return 'danger';
  }

  // 检查是否有人同意
  const hasApproved = row.flowDelegatedUserList?.some(user => user.confirmStatus === 1);
  if (hasApproved) {
    return 'success';
  }

  return 'info';
};

const getStatusValue = (row: ANY_OBJECT) => {
  // 如果是子行，显示确认状态
  if (row.isChild) {
    switch (row.confirmStatus) {
      case 1:
        return '已接受';
      case 2:
        return '已拒绝';
      default:
        return '待确认';
    }
  }

  // 检查是否过期
  const now = new Date();
  const endTime = new Date(row.endTime);
  if (now > endTime) {
    return '已过期';
  }

  // 检查是否有人同意
  const hasApproved = row.flowDelegatedUserList?.some(user => user.confirmStatus === 1);
  if (hasApproved) {
    return '生效中';
  }

  return '待确认';
};

// 委托范围字典
const delegateScopeDict = {
  user: '用户',
  dept: '部门',
  post: '岗位',
  dept_post: '部门岗位',
  role: '角色',
};

// 流程定义缓存
const processDefinitionDict = ref<Record<string, string>>({});

// 用户字典缓存
const userDict = ref<Record<string, ANY_OBJECT>>({});

// 加载用户字典数据
const loadUserDict = (userIds: string[]) => {
  if (!userIds.length) return Promise.resolve();

  const params = {
    widgetType: 'upms_user',
    fieldValues: userIds.join(','),
  };

  return SysCommonBizController.viewByIds(params, { showMask: false })
    .then(res => {
      const newDict = (res.data || []).reduce(
        (acc: Record<string, ANY_OBJECT>, user: ANY_OBJECT) => {
          acc[user.userId] = user;
          return acc;
        },
        {},
      );
      userDict.value = { ...userDict.value, ...newDict };
    })
    .catch(e => {
      console.warn(e);
    });
};

// 加载流程定义列表
const loadProcessDefinitionDict = () => {
  FlowEntryController.listDictByKey({})
    .then(res => {
      const dict: Record<string, string> = {};
      const list = Array.isArray(res.data) ? res.data : res.data?.dataList || [];
      list.forEach((item: ANY_OBJECT) => {
        dict[item.id] = item.name;
      });
      processDefinitionDict.value = dict;
    })
    .catch(e => {
      console.warn(e);
    });
};

// 格式化委托范围
const formatDelegateScope = (scope: string) => {
  if (!scope) return '';
  const scopes = scope.split(',');
  // 检查是否包含所有可能的范围
  const allScopes = ['user', 'dept', 'post', 'dept_post', 'role'];
  const isAll = allScopes.every(s => scopes.includes(s));
  if (isAll) return '全部';
  return scopes.map(s => delegateScopeDict[s] || s).join(',');
};

// 格式化流程定义
const formatProcessDefinition = (keys: string) => {
  if (!keys) return '全部';
  return keys
    .split(',')
    .map(key => processDefinitionDict.value[key] || key)
    .join(',');
};

/**
 * 加载代理数据
 */
const loadProcessAgentData = (params: ANY_OBJECT): Promise<TableData<ANY_OBJECT>> => {
  return new Promise((resolve, reject) => {
    FlowDelegateUserController.listMyDelegate(params)
      .then(res => {
        // 获取所有未缓存的用户ID
        const userIds = res.data.dataList.reduce((acc: string[], item) => {
          if (item.delegateUsers) {
            const ids = item.delegateUsers.split(',');
            ids.forEach(id => {
              if (!userDict.value[id]) {
                acc.push(id);
              }
            });
          }
          return acc;
        }, []);

        // 如果有未缓存的用户ID，先加载用户信息
        const loadDictPromise = userIds.length ? loadUserDict(userIds) : Promise.resolve();

        loadDictPromise.then(() => {
          // 转换数据为树形结构并添加用户详细信息
          const flatDataList = res.data.dataList.reduce((acc: ANY_OBJECT[], item) => {
            const users = item.delegateUsers?.split(',') || [];
            // 添加父级行
            const parentRow = {
              ...item,
              delegateUserNames: users
                .map(userId => userDict.value[userId]?.showName || userId)
                .join(', '),
              isChild: false,
            };
            acc.push(parentRow);

            // 添加子级行（被委托人列表）
            if (item.flowDelegatedUserList?.length) {
              item.flowDelegatedUserList.forEach((delegated, index) => {
                acc.push({
                  id: `${item.id}_${index}`,
                  parentId: item.id,
                  delegateUserNames: userDict.value[delegated.userId]?.showName || '',
                  confirmStatus: delegated.confirmStatus,
                  isChild: true,
                });
              });
            }

            return acc;
          }, []);

          // 使用 treeDataTranslate 转换为树形结构
          const treeData = treeDataTranslate(flatDataList, 'id', 'parentId');

          resolve({
            dataList: treeData,
            totalCount: res.data.totalCount,
          });
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};

/**
 * 列表数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadProcessAgentVerify = () => {
  return true;
};

const tableOptions: TableOptions<ANY_OBJECT> = {
  loadTableData: loadProcessAgentData,
  verifyTableParameter: loadProcessAgentVerify,
  paged: true,
};

const fragmentMyAgent = reactive({
  ProcessAgent: {
    impl: useTable(tableOptions),
  },
  isInit: false,
});

const refreshFragmentMyAgent = (reloadData = false) => {
  if (reloadData) {
    fragmentMyAgent.ProcessAgent.impl.refreshTable(true, 1);
  } else {
    fragmentMyAgent.ProcessAgent.impl.refreshTable();
  }
  fragmentMyAgent.isInit = true;
};

const onAddAgentClick = () => {
  Dialog.show(
    '新建委托',
    FormEditAgent,
    {
      area: ['600px', 'auto'],
    },
    {
      path: 'thirdEditAgent',
    },
    {
      width: '600px',
      height: '500px',
      pathName: '/thirdParty/thirdEditAgent',
    },
  )
    .then(() => {
      refreshFragmentMyAgent();
    })
    .catch(e => {
      console.warn(e);
    });
};

const onEditAgentClick = (row: ANY_OBJECT) => {
  Dialog.show(
    '编辑委托',
    FormEditAgent,
    {
      area: ['600px', 'auto'],
    },
    {
      rowData: row,
      path: 'thirdEditAgent',
    },
    {
      width: '600px',
      height: '500px',
      pathName: '/thirdParty/thirdEditAgent',
    },
  )
    .then(() => {
      refreshFragmentMyAgent();
    })
    .catch(e => {
      console.warn(e);
    });
};

const onDeleteClick = (row: ANY_OBJECT) => {
  ElMessageBox.confirm(`是否删除该委托记录？`, '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const params = {
        id: row.id,
      };
      FlowDelegateUserController.deleteDelegateUser(params)
        .then(() => {
          ElMessage.success('删除成功');
          fragmentMyAgent.ProcessAgent.impl.refreshTable();
        })
        .catch(e => {
          console.warn(e);
        });
    })
    .catch(() => {
      // do nothing
    });
};

const formInit = () => {
  // 加载流程定义字典
  loadProcessDefinitionDict();
  // 初始化表格数据
  refreshFragmentMyAgent(true);
};

onMounted(() => {
  formInit();
});

defineExpose({
  refreshFragmentMyAgent,
});
</script>
